package com.wee.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.bigtotoro.util.SharedPreferencesUtil;
import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.applib.controller.HXSDKHelper;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chatuidemo.DemoHXSDKHelper;
import com.easemob.chatuidemo.activity.ChatActivity;
import com.easemob.chatuidemo.db.DemoDBManager;
import com.easemob.chatuidemo.domain.RobotUser;
import com.easemob.chatuidemo.utils.UserUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wee.aircoach_user.CoachInfoActivity;
import com.wee.aircoach_user.CoachPlanActivity;
import com.wee.aircoach_user.Constant;
import com.wee.aircoach_user.MyApplication;
import com.wee.aircoach_user.R;
import com.wee.aircoach_user.RouleiActivity;
import com.wee.aircoach_user.YouzhiAcvitity;
import com.wee.aircoach_user.ZhushiActivity;
import com.wee.entity.MD5Util;
import com.wee.entity.User_detail;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;

/**
 * Created by Solomon on 2015/11/26.
 */
public class TrainingFragment extends Fragment implements View.OnClickListener,EMEventListener {
    /**
     * 跳转
     */
    public interface SkipCall {
        void skipTo(boolean isTrue);
    }
    private SkipCall skipCall;
    public SkipCall getSkipCall() {
        return skipCall;
    }
    public void setSkipCall(SkipCall skipCall) {
        this.skipCall = skipCall;
    }
    private View view;
    /**
     * 教师名称  动作名称   膳食单位 1,2,3   总需要天数  完成天数
     */
    private TextView teacherName, action_name, danwei_zhushi, danwei_youzhi, danwei_roulei, sumTian, okIian, itemest, tianshu1, item3_test,infor_num;
    private RelativeLayout yunname, yunname1, btn,layout_infor_hx;
    private LinearLayout zeliao, jindu;
    private String user_main;
    private User_detail data1;
    private Button beagin_btn;
    private ImageView imageView3;
    private ProgressBar download_pb;
    private List<EMConversation> conversationList = new ArrayList<EMConversation>();
    private int  it;
    private static int num=0;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.aaaamain, container, false);
        initView();
        return view;
    }

    private void initView() {
        ImageView imageView = (ImageView) view.findViewById(R.id.img_zs);
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("drawable://" + R.drawable.zhushi, imageView);
        ImageView imageView1 = (ImageView) view.findViewById(R.id.img_rl);
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("drawable://" + R.drawable.rou, imageView1);
        ImageView imageView2 = (ImageView) view.findViewById(R.id.img_yz);
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("drawable://" + R.drawable.youzhi, imageView2);
        imageView3 = (ImageView) view.findViewById(R.id.mainbg);
        /**饮食计划*/
        view.findViewById(R.id.roulei_yinshi).setOnClickListener(this);
        view.findViewById(R.id.zhushi_yinshi).setOnClickListener(this);
        view.findViewById(R.id.youzhi_yinshi).setOnClickListener(this);
        it= SharedPreferencesUtil.getInt(getActivity(), Constant.USERID);
/**按钮跳转*/
        view.findViewById(R.id.menu).setOnClickListener(this);
        view.findViewById(R.id.coach_xiangqing).setOnClickListener(this);
/**数据更改*/
        action_name = (TextView) view.findViewById(R.id.coach_plan_name);
        danwei_zhushi = (TextView) view.findViewById(R.id.zhushi_mn);
        danwei_youzhi = (TextView) view.findViewById(R.id.youzhi_mn);
        danwei_roulei = (TextView) view.findViewById(R.id.roulei_mn);
        infor_num= (TextView) view.findViewById(R.id.infor_num);
        tianshu1 = (TextView) view.findViewById(R.id.tianshu1);
        sumTian = (TextView) view.findViewById(R.id.zongshu);
        okIian = (TextView) view.findViewById(R.id.cishu);
        beagin_btn = (Button) view.findViewById(R.id.beagin_btn);
        itemest = (TextView) view.findViewById(R.id.itemest);
        item3_test = (TextView) view.findViewById(R.id.item3_test);
        view.findViewById(R.id.beagin_btn).setOnClickListener(this);
        zeliao = (LinearLayout) view.findViewById(R.id.zeliao);
        jindu = (LinearLayout) view.findViewById(R.id.jindu);
        layout_infor_hx= (RelativeLayout) view.findViewById(R.id.layout_infor_hx);
        yunname = (RelativeLayout) view.findViewById(R.id.yunname);
        yunname1 = (RelativeLayout) view.findViewById(R.id.yunname1);
        btn = (RelativeLayout) view.findViewById(R.id.btn);
        btn.setOnClickListener(this);
        download_pb = (ProgressBar) view.findViewById(R.id.my_progress);
        conversationList.addAll(loadConversationsWithRecentChat());
    }

    @Override
    public void onResume() {
        super.onResume();
        gethttp();
        EMChatManager.getInstance().registerEventListener(this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventConversationListChanged});
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**饮食计划*/
            case R.id.roulei_yinshi:
                Intent intent2 = new Intent(getActivity(), RouleiActivity.class);
                intent2.putExtra("weight", data1.getDiet().getProtein() + "");
                startActivity(intent2);
                break;
            case R.id.zhushi_yinshi:
                Intent intent4 = new Intent(getActivity(), ZhushiActivity.class);
                intent4.putExtra("weight", data1.getDiet().getCarbohydrate() + "");
                startActivity(intent4);
                break;
            case R.id.youzhi_yinshi:
                Intent intent3 = new Intent(getActivity(), YouzhiAcvitity.class);
                intent3.putExtra("weight", data1.getDiet().getFat() + "");
                startActivity(intent3);
                break;
            case R.id.menu:
                //环信 消息
                chat();
                break;
            /**教练详情*/
            case R.id.coach_xiangqing:
                Intent intent = new Intent(getActivity(), CoachInfoActivity.class);
                intent.putExtra("Coachid", data1.getCoach_id() + "");
                startActivity(intent);
                break;
            /**教练制定的计划**/
            case R.id.beagin_btn:
                try {
                    if (data1.getPlan().equals(null)) {
                        Toast.makeText(getActivity(), "您暂时还未有计划", Toast.LENGTH_SHORT).show();
                    } else {
                        Intent intent1 = new Intent(getActivity(), CoachPlanActivity.class);
                        intent1.putExtra("CoachDown", data1.getPlan().getId() + "");
                        //  intent1.putExtra("userId", data1.getId()+"");
                        intent1.putExtra("teacherId", data1.getCoach_id() + "");
                        startActivity(intent1);
                    }
                } catch (
                        Exception e
                        ) {
                }
                break;
            case R.id.btn:
                if (data1.getPlan_id() != 0) {
                    Intent intent1 = new Intent(getActivity(), CoachPlanActivity.class);
                    intent1.putExtra("CoachDown", data1.getPlan().getId() + "");
                    intent1.putExtra("userId", data1.getId() + "");
                    intent1.putExtra("teacherId", data1.getCoach_id() + "");
                    startActivity(intent1);
                } else {
                    Toast.makeText(getActivity(), "请等待教练给您定制计划", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    private void chat() {
        if(data1==null){
            return;
        }
        final String pwd = "abc123";
        final String coach = "coach_"+data1.getCoach().getId();
        final String user1 = "user_"+it;
        UserUtils.getUserInfo(coach).setNick(data1.getCoach().getName());
        UserUtils.getUserInfo(coach).setAvatar(data1.getCoach().getFigure());
        if (DemoHXSDKHelper.getInstance().isLogined()) {//进入主页面
            Intent intent = new Intent(getActivity(), ChatActivity.class);
            intent.putExtra("userId", coach);
            startActivity(intent);
            return;
        }else {
            EMChatManager.getInstance().login(user1, pwd, new EMCallBack() {
                @Override
                public void onSuccess() {
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    intent.putExtra("userId", coach);
                    startActivity(intent);
                }
                @Override
                public void onProgress(int arg0, String arg1) {
                    // TODO Auto-generated method stub
                }
                @Override
                public void onError(int arg0, String arg1) {
                    // TODO Auto-generated method stub

                }
            });
        }
    }

    /**
     * 解析字段
     */
    public void gethttp() {
        int exact=  SharedPreferencesUtil.getInt(getActivity(), Constant.USERTIME);
        user_main = Constant.USER_DETAIL +MD5Util.md5(exact)+ "&id=" + it + "&ver" + new Random().nextInt(9999);
     //
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, user_main,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        Gson gs = new Gson();
                        JsonObject jo = gs.fromJson(str, JsonObject.class);
                        JsonElement je = jo.get("status");
                        String status = je.getAsString();
                        if ("ok".equals(status)) {
                            JsonObject object = jo.getAsJsonObject("data");
                            data1 = gs.fromJson(object, User_detail.class);
                            try {
                                tianshu1.setText("" + data1.getPlan().getSchedule());
                                danwei_zhushi.setText("" + data1.getDiet().getCarbohydrate() + "g");
                                danwei_roulei.setText("" + data1.getDiet().getProtein() + "g");
                                danwei_youzhi.setText("" + data1.getDiet().getFat() + "g");
                                SharedPreferencesUtil.set(getActivity(), Constant.GENDER, data1.getGender());
                                SharedPreferencesUtil.set(getActivity(), Constant.USERNAME, data1.getName());
                                action_name.setText(data1.getPlan().getName() + "");
                            } catch (Exception r) {
                            }
                            /**教练没有制定计划*/
                            if (data1.getPlan_id() != 0) {
                                item3_test.setVisibility(View.VISIBLE);
                                //  itemest.setText("" + data1.getPlan().getDiscription());
                                okIian.setText("" + data1.getComplete());
                                sumTian.setText("" + data1.getPlan_count());
                                download_pb.setProgress(data1.getComplete());
                                download_pb.setMax(data1.getPlan_count());
                                yunname1.setVisibility(View.GONE);
                                jindu.setVisibility(View.VISIBLE);
                                yunname.setVisibility(View.VISIBLE);
                                beagin_btn.setVisibility(View.VISIBLE);
                                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(data1.getPlan().getFigure_preview(), imageView3);
                            } else {
                                item3_test.setVisibility(View.GONE);
                                itemest.setText("若您还未与私人教练沟通，可与教练联系");
                                //   itemest.setText(""+data1.getPlan().getDiscription());
                                jindu.setVisibility(View.GONE);
                                yunname.setVisibility(View.GONE);
                                yunname1.setVisibility(View.VISIBLE);
                                beagin_btn.setVisibility(View.GONE);
                                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("drawable://" + R.drawable.noplan, imageView3);
                            }
                            TextView name = (TextView) view.findViewById(R.id.coache_name);
                            name.setText(data1.getCoach().getName());
                            ImageView photo = (ImageView) view.findViewById(R.id.coach_photo);
                            if (data1.getCoach().getFigure() != null && data1.getCoach().getFigure().length() != 0) {
                                MyApplication.getInstance().getImageLoader().get(data1.getCoach().getFigure(), ImageLoader.getImageListener(photo, R.drawable.mian_nocoach, R.drawable.mian_nocoach), 200, 200);
                            }
                            try {
                                /***环信自己的信息**/
                                com.easemob.chatuidemo.domain.User userInfo = UserUtils.getUserInfo("user_" + data1.getId());
                                if (userInfo != null) {
                                    userInfo.setNick(data1.getName());
                                    userInfo.setAvatar(data1.getFigure());
                                }
                                //
                                /***环信教练的*/
                                String coach_name = "coach_" + data1.getCoach_id();
                                com.easemob.chatuidemo.domain.User hx_user = UserUtils.getUserInfo(coach_name);
                                hx_user.setNick(data1.getCoach().getName());
                                hx_user.setAvatar(data1.getCoach().getFigure());
                                RobotUser robotUser = new RobotUser();
                                robotUser.setUsername(coach_name);
                                robotUser.setNick(data1.getCoach().getName());
                                robotUser.setAvatar(data1.getCoach().getFigure());
                                List<RobotUser> robotUserList = new ArrayList<RobotUser>();
                                robotUserList.add(robotUser);
                                DemoDBManager.getInstance().saveRobotList(robotUserList);
                                //  EMConversation conversation = EMChatManager.getInstance().getConversation("user_" + it);
                                for (int i = 0; i < conversationList.size(); i++) {
                                    if (conversationList.get(i).getUserName().equals(coach_name)) {
                                        num=i;
                                    }
                                }
                                int a = conversationList.get(num).getUnreadMsgCount();

                                if (a > 0) {
                                    layout_infor_hx.setVisibility(View.VISIBLE);
                                    infor_num.setText("" + a);
                                } else {
                                    layout_infor_hx.setVisibility(View.GONE);
                                }
                            } catch (Exception r) {

                            }
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        System.out.println(e.getMessage());
                    }
                });

    }
    /**
     * 获取所有会话
     *
     * @param
     * @return
     */
    private List<EMConversation> loadConversationsWithRecentChat() {
        // 获取所有会话，包括陌生人
        Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations();
        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    //if(conversation.getType() != EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    //}
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;

    }
    /**
     * 根据最后一条消息的时间排序
     *
     * @param
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }


    /**
     * 监听事件
     */
    @Override
    public void onEvent(EMNotifierEvent event) {
        switch (event.getEvent()) {
            case EventNewMessage: // 普通消息
            {
                EMMessage message = (EMMessage) event.getData();

                // 提示新消息
                HXSDKHelper.getInstance().getNotifier().onNewMsg(message);
                refreshUI();
                break;
            }
            case EventOfflineMessage: {
                refreshUI();
                break;
            }
            case EventConversationListChanged: {
                refreshUI();
                break;
            }
            default:
                break;
        }
    }
    private void refreshUI() {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                // 刷新bottom bar消息未读数
                updateUnreadLabel();

            }
        });
    }
    /**进行环信刷新方法**/
    private void updateUnreadLabel() {
        conversationList.clear();
        conversationList.addAll(loadConversationsWithRecentChat());
        int a = conversationList.get(num).getUnreadMsgCount();
        if(a>0){
            layout_infor_hx.setVisibility(View.VISIBLE);
            infor_num.setText("" + a);
        }else{
            layout_infor_hx.setVisibility(View.GONE);
        }
    }
}
